﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KeyProviderImpl.cs" company="Marcin Jastrzebski">
//   Copyright (c) Marcin Jastrzebski (marcin@marcinj.net)
// </copyright>
// <summary>
//   The key provider implementation.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace mPassRT.Services
{
    using System.IO;
    using System.Threading.Tasks;

    using KeePassLib.Keys;

    using mPassRT.Controls;

    using PopupLibrary;

    /// <summary>The key provider implementation.</summary>
    public class KeyProviderImpl : IKeyProvider
    {
        #region Public Methods and Operators

        /// <summary>Gets the key for the specified database.</summary>
        /// <param name="databaseFileName">The database file name.</param>
        /// <param name="operation">The operation the key is needed for.</param>
        /// <returns>The key.</returns>
        public async Task<CompositeKey> GetKey(string databaseFileName, KeyOperation operation)
        {
            string fileName = Path.GetFileName(databaseFileName);
            DatabaseKeyControl control = CreateControl(operation, fileName);
            var key = await PopupManager.ShowAsync(control) as CompositeKey;
            return key;
        }

        #endregion

        #region Methods

        /// <summary>Creates the master key control.</summary>
        /// <param name="operation">The operation.</param>
        /// <param name="fileName">The file name.</param>
        /// <returns>The <see cref="DatabaseKeyControl"/>.</returns>
        private static DatabaseKeyControl CreateControl(KeyOperation operation, string fileName)
        {
            string format, commitButtonText;

            switch (operation)
            {
                default:
                    format = "Enter Master Key for {0}";
                    commitButtonText = "Unlock";
                    break;

                case KeyOperation.Create:
                    format = "Create new Master Key for {0}";
                    commitButtonText = "Create";
                    break;

                case KeyOperation.Change:
                    format = "Set new Master Key for {0}";
                    commitButtonText = "Set";
                    break;
            }

            return new DatabaseKeyControl
                       {
                           Title = string.Format(format, fileName), 
                           CommitButtonText = commitButtonText
                       };
        }

        #endregion
    }
}